<template>
  <div class="chart-page-container">
    <!-- 顶部下拉菜单 -->
    <div class="header-dropdown">
      <van-dropdown-menu>
        <van-dropdown-item v-model="selectedType" :options="typeOptions" @change="onTypeChange" />
      </van-dropdown-menu>
    </div>

    <!-- 时间周期切换标签 -->
    <div class="period-tabs">
      <van-tabs v-model:active="activePeriod" @change="onPeriodChange" color="#1e88e5" title-active-color="#1e88e5">
        <van-tab title="周" name="week"></van-tab>
        <van-tab title="月" name="month"></van-tab>
        <van-tab title="年" name="year"></van-tab>
      </van-tabs>
    </div>

    <!-- 统计信息卡片 -->
    <div class="stats-card">
      <div class="period-title">{{ periodTitle }}</div>
      <div class="stats-row">
        <div class="stat-item">
          <div class="stat-label">总{{ selectedType === 'expense' ? '支出' : '收入' }}</div>
          <div class="stat-value">{{ totalAmount.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">平均值</div>
          <div class="stat-value secondary">{{ averageAmount.toFixed(2) }}</div>
        </div>
      </div>
      <div class="max-amount">{{ maxAmount.toFixed(2) }}</div>

      <!-- ECharts 图表容器 -->
      <div ref="chartRef" class="chart-container"></div>
    </div>

    <!-- 排行榜 -->
    <div class="ranking-section">
      <div class="ranking-title">{{ selectedType === 'expense' ? '支出' : '收入' }}排行榜</div>
      <div v-if="rankingList.length > 0" class="ranking-list">
        <div v-for="item in rankingList" :key="item.category" class="ranking-item">
          <div class="ranking-info">
            <van-icon :name="item.icon" class="ranking-icon" />
            <span class="ranking-name">{{ item.category }}</span>
            <span class="ranking-percent">{{ item.percentage.toFixed(1) }}%</span>
          </div>
          <div class="ranking-bar-wrapper">
            <div class="ranking-bar" :style="{ width: item.percentage + '%' }"></div>
          </div>
          <div class="ranking-amount">{{ item.amount }}</div>
        </div>
      </div>
      <van-empty v-else description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { getChartData, getRankingData } from '@/api/index';


// 类型选择（支出/收入）
const selectedType = ref('expense');
const typeOptions = [
  { text: '支出', value: 'expense' },
  { text: '收入', value: 'income' }
];

// 周期选择
const activePeriod = ref('week');

// 图表实例
const chartRef = ref(null);
let chartInstance = null;

// 图表数据
const chartData = ref({
  dates: [],
  values: [],
  total: 0,
  average: 0,
  max: 0
});

// 排行榜数据
const rankingList = ref([]);

// 计算属性
const periodTitle = computed(() => {
  const periodMap = {
    week: '本周',
    month: '本月',
    year: '本年'
  };
  return periodMap[activePeriod.value] || '本周';
});

const totalAmount = computed(() => chartData.value.total || 0);
const averageAmount = computed(() => chartData.value.average || 0);
const maxAmount = computed(() => chartData.value.max || 0);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 如果已存在实例，先销毁
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  chartInstance = echarts.init(chartRef.value);
  
  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      },
      axisLabel: {
        color: '#999',
        fontSize: 11
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#999',
        fontSize: 11
      }
    },
    series: [
      {
        data: chartData.value.values,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: selectedType.value === 'expense' ? '#ff9800' : '#4caf50',
          width: 2
        },
        itemStyle: {
          color: selectedType.value === 'expense' ? '#ff9800' : '#4caf50',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: selectedType.value === 'expense' ? 'rgba(255, 152, 0, 0.3)' : 'rgba(76, 175, 80, 0.3)'
              },
              {
                offset: 1,
                color: selectedType.value === 'expense' ? 'rgba(255, 152, 0, 0.05)' : 'rgba(76, 175, 80, 0.05)'
              }
            ]
          }
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
};

// 获取图表数据（显示所有账本的总数据）
const fetchChartData = async () => {
  try {
    const res = await getChartData({
      type: selectedType.value,
      period: activePeriod.value
    });
    
    console.log("获取图表数据返回:", res);
    
    if (res) {
      // 确保数据存在并且格式正确
      chartData.value = {
        dates: res.dates || [],
        values: res.values || [],
        total: res.total || 0,
        average: res.average || 0,
        max: res.max || 0
      };
      
      console.log("处理后的图表数据:", chartData.value);
      
      // 等待 DOM 更新后初始化图表
      await nextTick();
      initChart();
    } else {
      console.warn("图表数据为空");
      showToast('暂无数据');
    }
  } catch (error) {
    console.error('获取图表数据失败:', error);
    showToast(error.message || '获取图表数据失败');
    // 清空数据
    chartData.value = {
      dates: [],
      values: [],
      total: 0,
      average: 0,
      max: 0
    };
  }
};

// 获取排行榜数据（显示所有账本的总数据）
const fetchRankingData = async () => {
  try {
    const res = await getRankingData({
      type: selectedType.value,
      period: activePeriod.value
    });
    
    console.log("获取排行榜数据返回:", res);
    
    if (res && Array.isArray(res) && res.length > 0) {
      rankingList.value = res.map(item => ({
        category: item.category,
        amount: item.amount,
        percentage: item.percentage,
        icon: getCategoryIcon(item.category)
      }));
      
      console.log("处理后的排行榜数据:", rankingList.value);
    } else {
      console.log("排行榜数据为空");
      rankingList.value = [];
    }
  } catch (error) {
    console.error('获取排行榜数据失败:', error);
    showToast(error.message || '获取排行榜数据失败');
    rankingList.value = [];
  }
};

// 获取分类图标
const getCategoryIcon = (category) => {
  const iconMap = {
    // 支出类别
    '餐饮': 'food-o',
    '购物': 'shopping-cart-o',
    '日用': 'bag-o',
    '交通': 'logistics',
    '蔬菜': 'flower-o',
    '水果': 'smile-o',
    '娱乐': 'music-o',
    '设置': 'setting-o',
    // 收入类别
    '工资': 'balance-pay',
    '兼职': 'gold-coin-o',
    '理财': 'chart-trending-o',
    '礼金': 'gift-o',
    '其他': 'ellipsis'
  };
  return iconMap[category] || 'balance-o';
};

// 类型切换
const onTypeChange = (value) => {
  selectedType.value = value;
  fetchChartData();
  fetchRankingData();
};

// 周期切换
const onPeriodChange = (name) => {
  activePeriod.value = name;
  fetchChartData();
  fetchRankingData();
};

// 窗口大小变化时重新渲染图表
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 生命周期
onMounted(() => {
  fetchChartData();
  fetchRankingData();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-page-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
}

.header-dropdown {
  background-color: #ffd54f;
  padding: 0;
}

:deep(.van-dropdown-menu__bar) {
  background-color: #ffd54f;
  box-shadow: none;
  height: 50px;
}

:deep(.van-dropdown-menu__title) {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.period-tabs {
  background-color: #ffd54f;
  padding: 0 16px;
}

:deep(.van-tabs__wrap) {
  background-color: transparent;
}

:deep(.van-tabs__nav) {
  background-color: transparent;
}

:deep(.van-tab) {
  color: rgba(51, 51, 51, 0.6);
  font-size: 16px;
}

:deep(.van-tab--active) {
  color: #333;
  font-weight: 600;
}

:deep(.van-tabs__line) {
  background-color: #333;
  width: 20px;
}

.stats-card {
  background-color: #ffd54f;
  padding: 16px;
  position: relative;
}

.period-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.stats-row {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
}

.stat-item {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: rgba(51, 51, 51, 0.7);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-value.secondary {
  font-size: 16px;
}

.max-amount {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart-container {
  width: 100%;
  height: 220px;
  margin-top: 8px;
}

.ranking-section {
  background-color: #fff;
  margin: 16px;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.ranking-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ranking-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ranking-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ranking-icon {
  font-size: 24px;
  color: #ff9800;
}

.ranking-name {
  flex: 1;
  font-size: 15px;
  color: #333;
}

.ranking-percent {
  font-size: 14px;
  color: #666;
}

.ranking-bar-wrapper {
  width: 100%;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.ranking-bar {
  height: 100%;
  background: linear-gradient(90deg, #ffd54f 0%, #ffb142 100%);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.ranking-amount {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  text-align: right;
}
</style>